<template>
  <el-card>
    <div>
      <div v-for="p in state" :key="p.id">
        <div class="all">
          <el-checkbox
            v-model="p.isCheckedAll"
            :indeterminate="p.isIndeterminate"
            @change="checkAllChange(p)"
            >{{ p.name }}</el-checkbox
          >
        </div>
        <el-checkbox-group v-model="p.checkeds" @change="gourpChange(p)">
          <el-checkbox v-for="c in p.children" :key="c.id" :label="c.id">
            {{ c.name }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <div class="flex">
        <el-button>清空</el-button>
        <el-button type="primary" @click="clickHandle">确定</el-button>
      </div>
    </div>
  </el-card>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  getRourceListByRoleIdApi,
  resourceListAllApi,
  resourceCategoryAllApi,
  allocResourceApi,
} from "./api";

const route = useRoute();
const router = useRouter();

type IState = IResourceCategoryModel & {
  children: IResourceModel[];
  //   这里面存当前这个分类选中的id
  checkeds: number[];
  //   全选状态
  isCheckedAll: boolean;
  //   部分选中状态
  isIndeterminate: boolean;
};

let state = ref<IState[]>([]);

if (route.query.id) {
  Promise.all([
    resourceCategoryAllApi(),
    resourceListAllApi(),
    getRourceListByRoleIdApi(parseInt(route.query.id as string)),
  ]).then((res) => {
    state.value = res[0].data.map((item) => ({
      ...item,
      children: [],
      checkeds: [],
      isCheckedAll: false,
      isIndeterminate: false,
    }));
    res[1].data.forEach((resource) => {
      const cate = state.value.find((cate) => cate.id === resource.categoryId);
      cate && cate.children.push(resource);
    });
    res[2].data.forEach((item) => {
      const pp = state.value.find((p) => p.id === item.categoryId);
      pp?.checkeds.push(item.id);
    });
    state.value.forEach((item) => {
      item.isCheckedAll = item.checkeds.length === item.children.length;
      item.isIndeterminate =
        item.checkeds.length < item.children.length && item.checkeds.length > 0;
    });
  });
}

const checkAllChange = (data: IState) => {
  if (!data.isCheckedAll) {
    data.checkeds = [];
  } else {
    data.checkeds = data.children.map((item) => item.id);
  }
  gourpChange(data);
};
const gourpChange = (data: IState) => {
  data.isCheckedAll = data.checkeds.length === data.children.length;
  data.isIndeterminate =
    data.checkeds.length < data.children.length && data.checkeds.length > 0;
};
// 确认
const clickHandle = () => {
  ElMessageBox.confirm("确认要分配权限吗？", "分配权限", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      allocResourceApi({
        roleId: parseInt(route.query.id as string),
        resourceIds: state.value.reduce<number[]>((prev, next) => {
          return prev.concat(next.checkeds);
        }, []),
      }).then((res) => {
        if (res.code === 200) {
          ElMessage.success("修改成功");
          router.push("/ums/role");
        }
      });
    })
    .catch(() => {});
};
</script>
<style lang="less" scoped>
.all {
  padding: 20px;
  background-color: #f2f6fc;
}
:deep(.el-checkbox-group) {
  display: grid;
  grid-template-columns: repeat(3, 33%);
  padding: 20px;
}

.flex {
  padding: 20px;
  display: flex;
  justify-content: center;
}
</style>
